<?php defined('InShopNC') or exit('Access Invalid!');?>
<?php echo BAIDUMAP_API_KEY; ?>	
<script type="text/javascript" src="<?php echo RESOURCE_PATH;?>/js/jquery.validation.min.js"></script>
<script type="text/javascript" src="<?php echo TEMPLATES_PATH;?>/js/area_array.js" charset="utf-8"></script>
<script type="text/javascript" src="<?php echo TEMPLATES_PATH;?>/js/common_select.js?v=<?php echo VERSION;?>" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="<?php echo TEMPLATES_PATH;?>/css/brand.css?v=<?php echo VERSION;?>"/>

<header class="layout head padding-small">
    <a href="javascript:back(true);" class="hBack float-left"></a>
    <h4 class="hTxt float-left text-center text-white"><?php echo $output['setting']['brand_name'];?>-品牌加盟</h4>
    <a href="javascript:;" id="btnJdkey" class="hHlep float-right"></a>
</header>

<style type="text/css">
 #poilist{ width: 100%; font-size: 12px;}
 .poiitem{ width: 100%; height: 40px; border-bottom:  1px solid #CCC; line-height: 40px; text-indent: 10px; overflow: hidden}
 .poiitem .title, .poiitem .address{ height: 20px; line-height: 20px; text-indent: 10px; overflow: hidden}
  .poiitem .address{ color: #CCC;}
 .poiitem_select{ color: #F00;}
</style>

<div class="brand_alliance">
	<div id="allmap" style="width: 100%;height: 200px; margin: 0"></div>
	<div id="poilist"></div>
	<form action="index.php?act=brand_alliance&op=alliance_add" method="post" id="formcompany">
		<dl class="relation_add">
			<dd><input type="text" name="true_name" id="true_name" class="text" value="" placeholder="姓名" /></dd>
			<dd><input type="text" name="mobile" id="mobile" class="text" value="" placeholder="手机号码" /></dd>
			<dd><input type="text" name="store_name" id="store_name" class="text" value="" placeholder="商城名称" /></dd>
                           <dd>
                                <input type="checkbox" name="agreement" id="agreement" value="1" />
                                <a url="index.php?act=brand_alliance&op=treaty&s_id=<?php echo $output['setting']['s_id'];?>" onClick="pclicked(this);">同意服务协议</a>
                          </dd>
			<dd>
				<div class="btn_area">
					<div><input type="submit" value="加盟" class="btn" id="subForm" /></div>
				</div>
			</dd>
		</dl>
		<input type="hidden" id="province" name="province" value="" />
		<input type="hidden" id="city" name="city" value="" />
		<input type="hidden" id="district" name="district" value="" />
		<input type="hidden" id="address" name="address" value="" />
		<input type="hidden" id="lng" name="lng" value="" />
		<input type="hidden" id="lat" name="lat" value="" />
		<input type="hidden" name="brand_id" value="<?php echo $output['setting']['brand_id'];?>" />
		<input type="hidden" name="brand_name" value="<?php echo $output['setting']['brand_name'];?>" />
		<input type="hidden" name="is_find" value="1" />
	</form>
</div>

<script type="text/javascript">
var DISTANCE = <?php echo $output['setting']['distance'];?>;
var my_icon  = '<?php echo SiteUrl; ?>/app/templates/images/mk_icon.png';
var pos_icon  = '<?php echo SiteUrl; ?>/app/templates/images/iconv_pos.png';
var map,fixed_point,circle;

//自定义控件--重新定位
function StaticsControl() {
	// 设置默认停靠位置右下角和偏移量  
	this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
	this.defaultOffset = new BMap.Size(10, 10);
}
StaticsControl.prototype = new BMap.Control();
StaticsControl.prototype.initialize = function (map) {
	var dom = document.createElement("div");
	var bg = document.createElement("img");
	bg.src = pos_icon;
	bg.style.width = '30px';
	bg.style.height = '30px';
	var object = dom.appendChild(bg);
	
	dom.id = 'rest_pos';
	dom.style.background = '#FFF';
	dom.style.width = '30px';
	dom.style.height = '30px';
	
	map.getContainer().appendChild(dom);
	return dom;
}

 function getLocation(point){
	$('#poilist').html('');
	var myGeo = new BMap.Geocoder();
	myGeo.getLocation(point, function (res) {
		$('#province').val(res.addressComponents.province);
		$('#city').val(res.addressComponents.city);
		$('#district').val(res.addressComponents.district);
		$('#address').val(res.address);
		$('#lng').val(res.point.lng);
		$('#lat').val(res.point.lat);
		
		var str = '<div class="poiitem poiitem_select" data-lng="'+res.point.lng+'" data-lat="'+res.point.lat+'" data-address="'+res.address+'" onclick="select_point(this)">'+res.address+'</div>';
		if(res.surroundingPois.length > 0){
			for( var i in res.surroundingPois){
				str += '<div class="poiitem" data-lng="'+res.surroundingPois[i].point.lng+'" data-lat="'+res.surroundingPois[i].point.lat+'" data-address="'+res.surroundingPois[i].address+'" onclick="select_point(this)"><div class="title">'+res.surroundingPois[i].title+'</div><div class="address">'+res.surroundingPois[i].address+'</div></div>';
			}
		}
		$('#poilist').append(str);
	});
}

//查询附近已加盟的数据
function allianceCheck(point){
	$.getJSON('index.php?act=brand_alliance&op=get_points',{brand_id:$('input[name=brand_id]').val(),mobile:$('input[name=mobile]').val(),brand_name:'<?php echo $output['setting']['brand_name'];?>',lng:point.lng,lat:point.lat,distance:DISTANCE},function(res){
		if(res.state){
			for(var i in res.list){
				var pointB = new BMap.Point(res.list[i].lng,res.list[i].lat);
				var marker = new BMap.Marker(pointB);
				map.addOverlay(marker);
				//标记信息
				var info = "<h4 style=\'margin:0 0 5px 0;padding:10px 0 0 0\'>"+res.list[i].store_name+"</h4><p style=\'margin:0;line-height:1.5;font-size:13px;text-indent:2em\'>"+res.list[i].pca_info+res.list[i].address+"</p>";
				var infoWindow = new BMap.InfoWindow(info);
				map.openInfoWindow(infoWindow,pointB);
			}
			$('#subForm').hide();
			alert('对不起，该品牌在本区域已有加盟店，您可以看看其他的热门品牌。');
                          pclicked('index.php?act=brand');
		}else{
			$('#subForm').show();
			alert('恭喜！当前地区可以加盟该品牌，您已屏蔽 '+res.num+' 家店家。');
		}
	});
}

if (window.plus) {
	 onPlusReady();
} else {
	 document.addEventListener("plusready", onPlusReady, false);
}

// 扩展API加载完毕，现在可以正常调用扩展API
function onPlusReady() {
	plus.geolocation.getCurrentPosition( function ( p ) {
		map = new BMap.Map("allmap");
		//清除所有覆盖物和信息窗口
		map.clearOverlays();
		map.closeInfoWindow();
		//添加重新定位控件
		var staticsCtrl = new StaticsControl();
		map.addControl(staticsCtrl);
		//设置定位位置中心和缩放比例
		var point = new BMap.Point(p.coords.longitude,p.coords.latitude);	 
		map.centerAndZoom(point,16);
		//添加当前定位点标记
		var marker = new BMap.Marker(point);
		map.addOverlay(marker);
		//绘制圆形区域
		circle = new BMap.Circle(point,DISTANCE,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.2, strokeOpacity: 0.2});
		map.addOverlay(circle);
		//添加中心点标记
		var icon = new BMap.Icon(my_icon, new BMap.Size(13,21),{anchor:new BMap.Size(2,21),imageOffset:new BMap.Size(-1,0)});
		fixed_point = new BMap.Marker(point,{icon: icon});
		map.addOverlay(fixed_point);
		getLocation(point);
		allianceCheck(point);
		//监听地图拖拽结束事件
		map.addEventListener('dragend', function(e){
			var rs = map.getCenter();
			fixed_point.setPosition(rs);
			getLocation(rs);
			//直接移动圆会产生重叠，所以将原本的圆清除重新添加圆----circle.setCenter(rs);
			map.removeOverlay(circle);
			circle = new BMap.Circle(rs,DISTANCE,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.2, strokeOpacity: 0.2});
			map.addOverlay(circle);
			allianceCheck(rs);
		});
		
	}, function ( e ) {
		window.location.href = 'index.php?act=brand_alliance&op=index_put&brand_id=<?php echo $output['setting']['brand_id'];?>';
	},{provider:'baidu',enableHighAccuracy:true} );
 }

function select_point(obj){
	$(obj).siblings('.poiitem').removeClass('poiitem_select');
	$(obj).addClass('poiitem_select');
	$('#address').val($(obj).data('address'));
	$('#lng').val($(obj).data('lng'));
	$('#lat').val($(obj).data('lat'));
	var point = new BMap.Point($(obj).data('lng'),$(obj).data('lat'));	 
	map.panTo(point);//地图平滑过渡
	fixed_point.setPosition(point);//标记点位置更改
	//直接移动圆会产生重叠，所以将原本的圆清除重新添加圆----circle.setCenter(rs);
	map.removeOverlay(circle);
	circle = new BMap.Circle(point,DISTANCE,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.2, strokeOpacity: 0.2});
	map.addOverlay(circle);
	allianceCheck(point);
}

$('#rest_pos').live('click',function(e){
	onPlusReady();
});
	
	
 //表单验证
$(function(){
		// 手机号码验证   
		jQuery.validator.addMethod("isMobile", function(value, element) {   
				var tel = /^1[3|5|7|8]\d{9}$/;
				return this.optional(element) || (tel.test(value));
		}, "手机号码输入错误");
		//姓名验证
		jQuery.validator.addMethod("isName", function(value, element) {
			return this.optional(element) || /^[\u4E00-\u9FA5]{2,15}$/.test(value);
		});
        $('#formcompany').validate({
            submitHandler:function(form){
			  var url = $('#formcompany').attr('action');
			  $.post('<?php echo SiteUrl;?>/app/'+url,$("form#formcompany").serialize(),function(data){
					Jump(data);
			  },'json');
             },
            rules : {
			  true_name:{
                    required:true,
				  isName : true
                },
			  mobile:{
                    required:true,
				  isMobile : true
                },
			  store_name:{
                    required:true
                },
                agreement:{
                    required:true
                },
            },
            messages : {
			   true_name:{
                    required:'请填写姓名',
				  isName : '姓名输入错误'
                },
			  mobile:{
                    required:'请填写手机号码',
				  isMobile : '手机号码输入错误'
                },
			  store_name:{
                    required:'请填写店名'
                },
                agreement:{
                    required:'请同意服务协议'
                },
            }
        });
});
</script>
